//
//  PlayManager.m
//  MusicDemo
//
//  Created by xalo on 16/6/16.
//  Copyright © 2016年 蓝鸥科技有限公司西安分公司. All rights reserved.
//

#import "PlayManager.h"
@interface PlayManager()

//播放器
@property (nonatomic,strong)AVPlayer *player;
// 定时器
@property (nonatomic,strong)NSTimer *timer;

@end

@implementation PlayManager

- (AVPlayer *)player {
    
    if (!_player) {
        _player = [[AVPlayer alloc]init];
    }
    return _player;
}

- (NSTimer *)timer {
    
    if (!_timer) {
        
        // 自动加入
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    }
    return _timer;
}
+ (instancetype)sharedManager {
    
static PlayManager *handle = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        handle = [[PlayManager alloc]init];
    });
    return handle;
}

// 暂停
- (void)pauseMusic {
    
    [self.player pause];
    [self closeTimer];
}

// 播放
- (void)playMusic {
    
    
    [self.player play];
    [self startTimer];
}

// 是否正在播放
- (BOOL)isPlaying {
    
    if (self.player.rate == 0){
  
        return NO;
     }    
    return YES;
}

// 准备去播放
- (void)prepareTopPlayMusicWithUrl:(NSString *)url {
    
    // 如果网址为空则不执行任何操作
    if (!url) {
        return;
    }
    // 判断，当前有没有正在播放的item
    if (self.player.currentItem) {
        
        //移除观察者
        [self.player.currentItem removeObserver:self forKeyPath:@"status"];
    }
    
    // 创建一个item
    AVPlayerItem *item = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:url]];
    
    // 观察item的加载状态
    [item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    
    // 替换当前item
    [self.player replaceCurrentItemWithPlayerItem:item];
    
    // 播放完成后自动跳到下一首
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playMusicEnd) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
}

// 自动播放下一首事件
- (void)playMusicEnd {
    
    if ([self.delegate respondsToSelector:@selector(playToNextMusic)]) {
        [self.delegate playToNextMusic];
        [[NSNotificationCenter defaultCenter]removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    }    
}

// 观察者事件
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    
    // 得到属性改变后的状态
    AVPlayerItemStatus status = [change[@"new"] integerValue];
    switch (status) {
        case AVPlayerItemStatusUnknown:
            NSLog(@"未知错误");
            break;
            case AVPlayerItemStatusReadyToPlay:
            
            //调用播放方法
            [self playMusic];
            NSLog(@"准备播放");
            break;
            case AVPlayerItemStatusFailed:
            NSLog(@"加载失败");
            break;
        default:
            break;
    }
}

// 获取总时长
- (NSInteger)fetchTotalTome {
    
    // 获取当前播放歌曲的总时间
    CMTime time = self.player.currentItem.duration;
    if (time.timescale == 0) {
        return 0;
    }
    // 获取当前播放秒数 = time.value/time.timescale
    return time.value/time.timescale;
}

// 获取当前播放歌曲的时间
- (NSInteger)fetchCurrentTime {
    
    CMTime time = self.player.currentItem.currentTime;
    if (time.timescale == 0) {
        return 0;
    }
    // 转化成秒数
    return time.value/time.timescale;
}

// 获取当前播放进度
- (CGFloat)fetchProgressValue {
    
    return [self fetchCurrentTime]/(CGFloat)[self fetchTotalTome];
}

// 将秒数转成类似00：00的时间格式
- (NSString *)changeSecondsTime:(NSInteger)time {
    
    NSInteger min = time / 60;
    NSInteger seconds = time % 60;
    return [NSString stringWithFormat:@"%.2ld:%.2ld",min,seconds];
}

// 快进、快退
- (void)playMusicWithSliderValue:(CGFloat)progress {
    
    // 滑动之前先暂停音乐
    [self pauseMusic];
    [self.player seekToTime:CMTimeMake([self fetchTotalTome]*progress, 1) completionHandler:^(BOOL finished) {
        
        //完成以后继续播放
        if (finished) {
            
            [self playMusic];
        }
    }];
}

// 定时器事件
- (void)timerAction {
   
    if ([self.delegate respondsToSelector:@selector(playManagerDelegateFetchTotalTime:currentTime:progress:)]) {
        
        NSString *totalTime = [self changeSecondsTime:[self fetchTotalTome]];
        NSString *currentTime = [self changeSecondsTime:[self fetchCurrentTime]];
        CGFloat progress = [self fetchProgressValue];
        [self.delegate playManagerDelegateFetchTotalTime:totalTime currentTime:currentTime progress:progress];
    }
    
}

// 开启定时器
- (void)startTimer {
    
    [self.timer fire];
}

// 关闭定时器
- (void)closeTimer {
   
    [self.timer invalidate];
    
    // 失效之后必须置空
    self.timer = nil;
}









@end
